package com.waimai1.waimai.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.dto.CreatePPOrderDto;
import com.waimai1.waimai.dto.GetOpenShopDto;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.entity.Pinpai;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.HwService;
import com.waimai1.waimai.service.MyOrderService;
import com.waimai1.waimai.service.PinpaiService;
import com.waimai1.waimai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/pinpai")
public class PinPaiController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${Hw.userNo}")
    private String userNo;
    @Value("${jiesuoKey}")
    private String jiesuoKey;
    @Value("${Hw.notifyUrl}")
    private String notifyUrl;
    @Autowired
    private MyOrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private HwService hwService;
    @Autowired
    private PinpaiService pinpaiService;
    @RequestMapping(value={"/pinpai/{pageId}"},method=RequestMethod.GET)
    public R<Map<String,Object>> pinpai(@PathVariable Integer pageId){
        Page<Pinpai> page=new Page<>(pageId,20);
        IPage<Pinpai> pinpaiPage=pinpaiService.page(page);
        List<Pinpai> pinpaiList=pinpaiPage.getRecords();
        Long total=pinpaiPage.getTotal();
        Map<String,Object> res=new HashMap<>();
        res.put("pinpaiList",pinpaiList);
        res.put("total",total);
        return R.success(res);
    };
    @GetMapping("/getPinPai")
    public R<Object> getPinPai() throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI);
        Object res = hwService.getHwData(argsMap, sign, Utils.HW_PINPAI);
        return R.success(res);
    }

    @PostMapping("/getCity")
    public R<Object> getCity(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_CITY);
        Object res = hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_CITY);
        return R.success(res);
    }

    @PostMapping("/getOpenShop")
    public R<Object> getOpenShop(@RequestBody GetOpenShopDto getOpenShopDto) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        //如果是喜茶和奈雪茶，则输入地区参数，暂时不加，后面实现
        if (redisTemplate.hasKey("OpenShop:" + getOpenShopDto.getBrand_id() + getOpenShopDto.getProvince_name() + getOpenShopDto.getCity_name())) {
            String jsonData=(String)redisTemplate.opsForValue().get("OpenShop:" + getOpenShopDto.getBrand_id() + getOpenShopDto.getProvince_name() + getOpenShopDto.getCity_name());
            return R.success(JSON.parseObject(jsonData));
        }
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", getOpenShopDto.getBrand_id(), "province_name", getOpenShopDto.getProvince_name(), "city_name", getOpenShopDto.getCity_name(), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_OPENSHOP);

        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_OPENSHOP);
//        return R.success(res);
        if (res.get("error_code").equals(200)) {
            String jsonData=JSON.toJSONString(res.get("data"));
            redisTemplate.opsForValue().append("OpenShop:" + getOpenShopDto.getBrand_id() + getOpenShopDto.getProvince_name() + getOpenShopDto.getCity_name(),jsonData);
            redisTemplate.expire("OpenShop:" + getOpenShopDto.getBrand_id() + getOpenShopDto.getProvince_name() + getOpenShopDto.getCity_name(), 300, TimeUnit.SECONDS);
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }

    @PostMapping("/getAllShop")
    public R<Object> getAllShop(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        //如果是喜茶和奈雪茶，则输入地区参数，暂时不加，后面实现
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "province_name", map.get("province_name"), "city_name", map.get("city_name"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_ALLSHOP);

        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_ALLSHOP);
        if (res.get("error_code").equals(200)) {
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }

    @PostMapping("/getOpenMenu")
    public R<Object> getOpenMenu(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "restaurant_id", map.get("restaurant_id"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_OPENMENU);
        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_OPENMENU);
        if (res.get("error_code").equals(200)) {
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }

    @PostMapping("/getAllMenu")
    public R<Object> getAllMenu(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "restaurant_id", map.get("restaurant_id"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_ALLMENU);
        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_ALLMENU);
        if (res.get("error_code").equals(200)) {
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }

    @PostMapping("/getMenuDetail")
    public R<Object> getMenuDetail(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "restaurant_id", map.get("restaurant_id"), "product_id", map.get("product_id"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_MENUDETAIL);
        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_MENUDETAIL);
        if (res.get("error_code").equals(200)) {
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }

    //创建麻花品牌订单
    @PostMapping("/createPPOrder")
    public R<Object> createPPOrder(@RequestBody CreatePPOrderDto ppOrder) throws Exception {
        //验证签名
        TreeMap<String, Object> signMap=new TreeMap<>();
        signMap.put("totalPrice",String.format("%.2f", ppOrder.getTotalPrice()));
        String sign=Utils.getHwSign(signMap, jiesuoKey,"pinpai");
        if(!sign.equals(ppOrder.getSign())){
            throw new NotErrorException(EnumException.NO_SIGN);
        }
        //创建订单和详情单
        ppOrder.setStatus(Utils.STATUS_WAIT_PAY);
        ppOrder.setOpenid(BaseContext.getopenId());
        ppOrder.setAcid(BaseContext.getAcid());
        if(orderService.save(ppOrder)){
            //添加延时关单功能
            int delayTime=5 * 60 * 1000;
            redisTemplate.opsForZSet().add("cancelOrder",ppOrder.getOutTradeNo(),System.currentTimeMillis()+delayTime);
        }
//        if (!BaseContext.getPhone().equals(ppOrder.getTakePhone())) {
//            userService.updatePhone(ppOrder);
//        }
        return R.success("创建订单成功");
    }

    @PostMapping("/searchOrder")
    public R<Object> SearchOrder(@RequestBody Map<String, Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String, Object> argsMap = Utils.getParams("user_no", userNo, "brand_id", map.get("brand_id"), "tradeNo", map.get("tradeNo"), "orderNo", map.get("orderNo"), "timestamp", time);
        String sign = hwService.getHwSign(argsMap, Utils.HW_PINPAI_SEARCH_ORDER);
        Map<String, Object> res = (Map<String, Object>) hwService.getHwData(argsMap, sign, Utils.HW_PINPAI_SEARCH_ORDER);
        if (res.get("error_code").equals(200)) {
            return R.success(res.get("data"));
        }
        throw new NotErrorException((Integer) res.get("error_code"), res.get("error_msg").toString());
    }
//    @PostMapping("/testHw")
//    public void testHw(@RequestBody  Map<String,Object> map) throws UnsupportedEncodingException {
//         hwService.createOrder((Integer) map.get("brandId"),(Integer)map.get("restaurantId"),(String)map.get("phone"),(String)map.get("eatType"),(String)map.get("productsJson"),(String)map.get("outTradeNo"));
//
//    }

}
